package com.bieyang.anjia.ui.activity;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.bieyang.anjia.R;
import com.bieyang.anjia.module.NewsInfo;
import com.bieyang.anjia.sqlitedatabase.AnjiaSQLiteOpenHelper;
import com.bieyang.anjia.sqlitedatabase.SqliteOperation;
import com.bieyang.anjia.ui.adapter.NewsAdapter;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.Show;
import com.bieyang.anjia.utils.ShowProgress;
import com.bieyang.anjia.utils.SubUtils;

/**
 * 查看更多资讯
 * */
public class AcFindNews extends BaseFlingActivity {
	Button btnBack;
	RelativeLayout rlYuShe, newsDetail;
	Context con;
	int pageSize = 10;
	boolean sqlAllQueryed;
	private String[] items;
	private SubUtils subUtils = new SubUtils();
	/**
	 * 底部加载更多
	 */
	View footView;
	List<NewsInfo> newsList = new ArrayList<NewsInfo>();
	NewsAdapter adapter;
	ListView lvNews;
	SqliteOperation sqlOperation;
	ShowProgress showProgress;
	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
			case Constants.GET_NEWS_SUCESS:
				// Log.e("msg.arg1", msg.arg1 + "");
				refreshData();
				if (null != showProgress) {
					showProgress.dismiss();
				}
				break;
			case Constants.GET_NEWS_FAIL:
				if (null != showProgress) {
					showProgress.dismiss();
				}
				Show.toast(AcFindNews.this, R.string.tip_get_news_fail);
				break;
			default:
				break;
			}
		};

	};

	/**
	 * 链接数据库
	 */
	void openDatabase() {
		if (null == sqlOperation) {
			sqlOperation = new SqliteOperation(con,
					AnjiaSQLiteOpenHelper.dbName, AnjiaSQLiteOpenHelper.version);
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.find_news);
		con = AcFindNews.this;
		items = new String[] { getString(R.string.delete_news) };
		openDatabase();
		initView();
		initData();
	}

	private void initView() {
		footView = getLayoutInflater().inflate(R.layout.pull_refresh, null);
		footView.setVisibility(View.GONE);
		footView.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				footView.setEnabled(false);
				refreshData();
			}
		});
		OnClick onClick = new OnClick();
		btnBack = (Button) findViewById(R.id.btnBack);
		btnBack.setOnClickListener(onClick);
		lvNews = (ListView) findViewById(R.id.lvNews);
		lvNews.addFooterView(footView);
		adapter = new NewsAdapter(con, newsList);
		lvNews.setAdapter(adapter);
		lvNews.setOnItemClickListener(new OnItemClick());
		lvNews.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent,
					final View view, final int position, long id) {
				final NewsInfo info = newsList.get(position);
				new AlertDialog.Builder(con, AlertDialog.THEME_HOLO_LIGHT)
						.setTitle(
								12 > info.title.length() ? info.title
										: info.title.substring(0, 11) + "...")
						.setItems(items, new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								switch (which) {
								case 0:
									try {
										sqlOperation.update("newsinfo",
												"_id=?",
												new String[] { info._id + "" },
												"isdelete", "T");
										subUtils.startDeleteAnimation(view,
												position, newsList, adapter);
									} catch (Exception e) {
										e.printStackTrace();
									}
									break;
								default:
									break;
								}
							}
						}).show();

				return true;
			}
		});
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	void initData() {
		if (null == showProgress) {
			showProgress = SubUtils.showProgress(con);
		}
		showProgress.show();
		App.netManager.getNewsMore(con, handler,
				sqlOperation.queryColumn("newsinfo", "submittime", null, null));
	}

	void refreshData() {
		List<NewsInfo> queryList = sqlOperation.queryNews("isdelete=?",
				new String[] { "F" }, newsList.size() + "," + pageSize);
		int count = queryList.size();
		if (count < 10) {
			footView.setVisibility(View.GONE);
			lvNews.removeFooterView(footView);
		} else {
			footView.setEnabled(true);
			footView.setVisibility(View.VISIBLE);
		}
		newsList.addAll(queryList);
		if (0 == newsList.size()) {
			Show.toast(this, R.string.no_data);
		}
		adapter.notifyDataSetChanged();
	}

	class OnItemClick implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {
			Intent intent = new Intent(con, AcFindNewsDetail.class);
			Bundle bundle = new Bundle();
			bundle.putSerializable("newsInfo", newsList.get(position));
			intent.putExtras(bundle);
			startActivityForResult(intent, 0);
		}

	}

	class OnClick implements android.view.View.OnClickListener {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btnBack:
				finish();
				break;
			default:
				break;
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (0 == requestCode) {
			int size = newsList.size();
			newsList.clear();
			newsList.addAll(sqlOperation.queryNews("isdelete=?",
					new String[] { "F" }, size + ""));
			adapter.notifyDataSetChanged();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}
}